<?php
declare (strict_types=1);

namespace app\admin\controller;

use addons\BuilderPlus\components\Button;
use addons\BuilderPlus\components\Column as Col;
use addons\BuilderPlus\components\Edit;
use addons\BuilderPlus\facade\Table;
use think\facade\View;

class Menu extends Base
{
    public function getOptions(): array
    {
        return [
            'pk'    => 'id',
            'model' => \app\common\model\Menu::class,
            'with'  => ['children']
        ];
    }

    public function index()
    {
        return Table::init($this)
            ->addColumns([
                ['title', '名称', fn(Col $col) => $col->align('left')->templet('<i class="layui-icon {{d.css}}"></i> {{d.title}}'), fn(Edit $e) => $e->require()],
                ['name', '节点', null, fn(Edit $e) => $e->require()],
                ['sub_title', '简称', null, fn(Edit $e) => $e->require()],
                ['css', '图标', fn(Col $col) => $col->hide()->templet('<i class="layui-icon {{d.css}}"></i>'), fn(Edit $e) => $e->require()],
                ['sort', '排序', fn(Col $col) => $col->fastSort(), fn(Edit $e) => $e->number()],
                ['status', '状态', fn(Col $col) => $col->switch('开启|关闭', '1|0')->fixed('right')]
            ])
            ->addTopButtons(['add', 'deleteAll'])
            ->addRightButtons(['edit',
                'addSubMenu' => fn(Button $b) => $b->title('添加子菜单')
                    ->event('od')
                    ->class('warm')
                    ->url(url('menu/add')->build(), 'pid:id')
                    ->scriptlet('{{# if (d.children.length > 0){ }}', '{{# } }}')
            ], 160)
            ->addSearch([
                ['title__sub_title', '名称/简称', fn($search) => $search->condition('Like')]
            ])
            ->enableTree(false, true)
            ->fetch();
    }

    public function add(string $tpl = '')
    {
        $param = $this->request->get();
        if (!empty($param['pid'])) {
            $parent = $this->getOptions()['model']::where('id', $param['pid'])->find();
            $html = builderFormInit([
                'title' => '上级菜单',
                'value' => $parent->title
            ])->getFormItemInputHtml('text', "<input type='hidden' name='pid' value='{$parent->id}'/>", true);
            View::assign('appendHtml', $html);
        }
        return parent::add($tpl);
    }
}
